<template>
  <div class="phonev" @click="getSMS">
      <span v-show="state === 'init'">获取验证码</span>
      <span v-show="state === 'loading'">{{ downNum }}s</span>
      <span v-show="state === 'finished'">重新发送</span>  
  </div>
</template>

<script>
  export default {
    data () {
      return {
        state: 'init', // init -> loading -> finished
        downNum: 60,
        timer: null
      }
    },
    watch: {
      state (newValue) {
        if (newValue === 'loading') {
          this.countDown()
        }
        // 初始化状态
        if (newValue === 'init') {
          this.downNum = 60
          this.timer = null
        }
      },
      downNum (newValue) {
        if (newValue === 0) {
          this.state = 'finished'
          clearInterval(this.timer)
        }
      }
    },
    methods: {
      countDown () {
        this.timer = null
        this.timer = setInterval(() => {
          this.downNum--
        }, 1000)
      },
      getSMS () {
        if (this.state === 'loading') {
          return
        }
        this.downNum = 60
        this.state = 'loading'
        this.$emit('click')
      }
    }
  }
</script>

<style lang='scss'>
  @import '../../common/scss/_variable.scss';
  .phonev {
    span {
      display: inline-block;
      border-radius: 50px;
      background: #fcc1bb;
      color: $base-fff;
      padding: 20px 30px 15px 30px;
      min-width: 80px;
      font-size: 26px;
      text-align: center;
      &:nth-child(2) {
        background: $base-fff;
        color: #999;
        border: 1px solid lighten(#ff4133, 17);
      }
    }
  }
</style>
